const { promisify } = require('util');
const path = require('path')

const download = promisify(require('download-git-repo'));

const { vueGitRepo } = require('../config/repo_config');
const { spawnCommand } = require('../utlis/terminal');
const { ejsCompile, mkdirSync, writeFile } = require('../utlis/file')

// 创建项目
const createProjectAction = async(project) => {
  console.log('nxpm helps you create your project, please wait a moment~');
  // 1.拉取仓库模板
  await download(vueGitRepo, project, { clone: true });
  console.log('clone项目完毕');
  // 2. npm install => windows or mac
  const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  await spawnCommand(npm, ['install'], { cwd: `./${project}` });
  // 3. npm run serve
  await spawnCommand(npm, ['run', 'serve'], { cwd: `./${project}` });
}

// 添加组件
const addComponentAction = async (name, dest) => {
  // 1.获取模板路径
  const templatePath = path.resolve(__dirname, '../template/component.vue.ejs');
  const cpnPath = dest.replace('router', 'views').replace('src', '@') + `/${name}.vue`;
  
  // 2.模板编译根据指令转化
  const result = await ejsCompile(templatePath, {name, lowerName: name.toLowerCase(), cpnPath});

  // 3.写入文件
  // 判断文件是否存在，否则创建文件
  mkdirSync(dest);
  const targetPath = path.resolve(dest, `${name}.vue`);
  writeFile(targetPath, result)
}

module.exports = {
  createProjectAction,
  addComponentAction
}